<template>
  <div class="vehicle-detail-container">
    <div class="back-button">
      <el-button @click="goBack" icon="el-icon-arrow-left">返回列表</el-button>
    </div>
    
    <el-row :gutter="20" v-if="vehicle">
      <el-col :span="12">
        <div class="vehicle-image">
          <img :src="getImageUrl(vehicle.imageUrl)" alt="车辆图片" @error="handleImageError">
        </div>
      </el-col>
      <el-col :span="12">
        <el-card class="vehicle-info">
          <h1>{{ vehicle.brand }} {{ vehicle.model }}</h1>
          <el-divider></el-divider>
          
          <el-descriptions :column="1" border>
            <el-descriptions-item label="车牌号">{{ vehicle.plateNumber }}</el-descriptions-item>
            <el-descriptions-item label="颜色">{{ vehicle.color }}</el-descriptions-item>
            <el-descriptions-item label="座位数">{{ vehicle.seatCount }}座</el-descriptions-item>
            <el-descriptions-item label="所属车行">{{ shopName }}</el-descriptions-item>
            <el-descriptions-item label="日租价格">
              <span class="price">¥ {{ vehicle.dailyPrice }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(vehicle.status)">{{ getStatusText(vehicle.status) }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <div class="action-buttons">
            <el-button 
              type="primary" 
              size="large" 
              :disabled="vehicle.status !== 1"
              @click="rentVehicle"
            >
              立即租车
            </el-button>
            <el-button type="info" size="large" @click="showVehicleOnMap">查看位置</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-empty v-else description="加载中..." :image-size="200"></el-empty>
    
    <!-- 位置地图对话框 -->
    <el-dialog title="车辆位置" v-model="mapDialogVisible" width="60%">
      <div class="map-container">
        <div class="location-info">
          <h3>车辆当前位置</h3>
          <p>{{ vehicle?.currentLocation || '暂无位置信息' }}</p>
        </div>
        <img :src="'/assets/map-placeholder.png'" alt="地图" @error="e => e.target.src = '/assets/no-image.png'">
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="mapDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getVehicleDetail } from '@/api/vehicle'

const route = useRoute()
const router = useRouter()
const vehicle = ref(null)
const shopName = ref('未知车行') // 这里应该从车行服务获取
const mapDialogVisible = ref(false)

// 图片URL处理函数
const getImageUrl = (url) => {
  if (!url) return '/assets/no-image.png';
  
  // 如果是绝对URL（以http开头），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    // 如果是placeholder站点且有连接问题，使用本地占位图
    if (url.includes('via.placeholder.com')) {
      return '/assets/no-image.png';
    }
    return url;
  }
  
  // 如果是相对URL，需要检查格式并调整
  
  // 1. 修正端口问题：从3000改为8081
  if (url.includes('localhost:3000')) {
    url = url.replace('localhost:3000', 'localhost:8081');
  }
  
  // 2. 如果URL不以/开头，添加/
  if (!url.startsWith('/')) {
    url = '/' + url;
  }
  
  // 拼接服务器地址，使用正确的端口8081
  const host = window.location.protocol + '//' + window.location.hostname + ':8081';
  return host + url;
}

// 图片加载错误处理
const handleImageError = (e) => {
  if (e && e.target) {
    // 使用本地资源文件夹中的占位图
    e.target.src = '/assets/no-image.png';
  }
}

// 获取车辆状态文字
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '维修中'
    case 1:
      return '可租用'
    case 2:
      return '已租出'
    default:
      return '未知状态'
  }
}

// 获取车辆状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'success'
    case 2:
      return 'info'
    default:
      return 'info'
  }
}

// 获取车辆详情
const fetchVehicleDetail = async () => {
  try {
    const vehicleId = route.params.id
    if (!vehicleId) {
      ElMessage.error('无效的车辆ID')
      router.push('/vehicle/list')
      return
    }
    
    const res = await getVehicleDetail(vehicleId)
    vehicle.value = res.data
    
    // 这里可以通过车行ID获取车行名称
    shopName.value = `车行ID: ${vehicle.value.shopId}`
  } catch (error) {
    console.error('获取车辆详情失败:', error)
    ElMessage.error('获取车辆详情失败')
  }
}

// 返回列表
const goBack = () => {
  router.push('/vehicle/list')
}

// 租车
const rentVehicle = () => {
  if (!localStorage.getItem('token')) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  router.push(`/order/create/${vehicle.value.id}`)
}

// 显示车辆位置地图
const showVehicleOnMap = () => {
  mapDialogVisible.value = true
}

// 组件挂载时获取车辆详情
onMounted(() => {
  fetchVehicleDetail()
})
</script>

<style scoped>
.vehicle-detail-container {
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.vehicle-image {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  height: 300px;
}

.vehicle-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.vehicle-info {
  height: 100%;
}

.vehicle-info h1 {
  margin-top: 0;
  color: #303133;
}

.price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  gap: 15px;
}

.map-container {
  width: 100%;
  height: 500px;
  display: flex;
  flex-direction: column;
}

.location-info {
  margin-bottom: 15px;
}

.map-container img {
  width: 100%;
  height: 400px;
  object-fit: cover;
}
</style> 